/*
 *  Copyright (C) 2009 Dominik Psenner
 * 
 *   This file is part of WebDAV4JD.
 *
 *  WebDAV4JD is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  WebDAV4JD is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with project-blog.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package com.lab9.webdav4jd.api.impl.datasource;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

import com.lab9.webdav4jd.api.DataSource;
import com.lab9.webdav4jd.api.exceptions.UnsupportedException;
import com.lab9.webdav4jd.api.properties.ResponseCode;
import com.lab9.webdav4jd.core.HttpHeader;
import com.lab9.webdav4jd.core.HttpRequest;
import com.lab9.webdav4jd.core.HttpResponse;

/**
 * @author dominik
 * 
 */
public class NativeJava implements DataSource {
	
	private final String url;
	
	public NativeJava(final String url) {
		this.url = url;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getURL() {
		return url;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public HttpResponse fetch(final HttpRequest request) throws IOException {
		final URLConnection con = request.getURL().openConnection();
		
		final int responseCode = 0; // TODO fix this
		
		final List<HttpHeader> headers = new LinkedList<HttpHeader>();
		for (final Entry<String, List<String>> e : con.getHeaderFields().entrySet()) {
			final String[] arr = new String[e.getValue().size()];
			headers.add(new HttpHeader(e.getKey(), e.getValue().toArray(arr)));
		}
		
		byte[] bytes = new byte[0];
		final InputStream is = con.getInputStream();
		try {
			final byte[] tmp = new byte[2048];
			int r = -1;
			while ((r = is.read(tmp)) > 0) {
				final byte[] tmp2 = new byte[bytes.length + r];
				// FIXME this may bang up the computer and should be improved
				// FIXME additionally I'm not sure if this could even be a possible security hole
				for (int i = 0; i < bytes.length + r; i++) {
					if (i < bytes.length) {
						tmp2[i] = bytes[i];
					}
					else {
						tmp2[i] = tmp[i];
					}
				}
				bytes = tmp2;
			}
		}
		finally {
			is.close();
		}
		
		try {
			return new HttpResponse(ResponseCode.get(responseCode), headers, bytes);
		}
		catch (final UnsupportedException e1) {
			throw new IOException(e1);
		}
	}
}
